package com.tianqu.tms.www.member.action;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.www.member.actionform.MemImgInputActionForm;
import com.tianqu.tms.www.member.viewhelper.MemberInputViewHelper;

/**
 * 
 * 图片上传结果页面
 * 
 * @author tianshifu
 *
 */
public class MemCreationImageResultAction extends TmsAction {

	private static final String POSITION = "position";//图片位置
	private static final String IMGLIST = "imgList";//用于存放图片对象的list
	private static final String SEEPIC = "seePic";
	private static final String UPPIC = "upPic";
	private static final String IMAGEERROR="imageError";
	private static final String FLAG = "flag";
	
	private Logger logger = Logger.getLogger(MemCreationImageResultAction.class);
	
	@SuppressWarnings("unchecked")
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		
		String position = (String)uc.getAttribute(POSITION);

		String forward = TmsConstants.BLANK;
		
		//从form中
		MemImgInputActionForm carImgForm = (MemImgInputActionForm)form;
		MemberInputViewHelper viewhelp = (MemberInputViewHelper)uc.getAttribute(TmsConstants.VIEWHELP);
		if(carImgForm.getBackButton() != null){
			viewhelp.setSeePicFlag(false);
			uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
			request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
			carImgForm.setBackButton(null);
			viewhelp.setImageFlag("0");
			forward = UPPIC;
		}else{
			//显示图片的button
			if(carImgForm.getSeePicButton() != null){
				//String imgPath = carImgForm.getImgPath();
			FormFile formfil =  carImgForm.getImgPath();
			
			//判断图片是否正确
			if(imageAll(formfil)){
				  setErrorsToRequest(request, TmsConstants.I0015 ,null);
				  uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
					request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
		            return mapping.findForward(IMAGEERROR);	
			}else if(formfil.getFileSize() > 1048576){
				setErrorsToRequest(request, TmsConstants.I0018 ,null);
				viewhelp.setImageFlag("0");
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
				request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
	            return mapping.findForward(IMAGEERROR);	
			}
			
			viewhelp.setImageFlag("1");
			String path =ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY));
			    String img = System.currentTimeMillis()+".jpg";//图片名称
				FileOutputStream fileOutput = new FileOutputStream(new File(path+ img) );
			    fileOutput.write(formfil.getFileData());
	            fileOutput.flush();
				viewhelp.setSeePic(ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY) + img));
				//前台显示出隐藏部分的图片
				viewhelp.setSeePicFlag(true);
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
				//返回当前页面 要对form的值重新set
				carImgForm.setSeePicButton(null);
				request.setAttribute(TmsConstants.VIEWHELP, viewhelp);
				forward = SEEPIC;
			}else{

				//把一组数据打包存如entity中
				CarImage entity  = CarImage.getInstance();
				entity.setImgPath(viewhelp.getSeePic());//这个Path需要处理一下
				entity.setImgKey(position);//给个标识
				if("1".equals(position)){
					viewhelp.setOrgPhoto(viewhelp.getSeePic());// 组织机构代码证图片
				}else if("2".equals(position)){
					viewhelp.setBusinessPhoto(viewhelp.getSeePic());// 营业执照编号图片
				}else if("3".equals(position)){
					viewhelp.setCardPhoto(viewhelp.getSeePic());// 法人身份证图片
				} else if("5".equals(position)){
					viewhelp.setMemberZipCode(viewhelp.getSeePic());// 法人身份证图片
					}
				//前台不显示隐藏部分的图片
				viewhelp.setSeePicFlag(false);
				//放到一个list中，每次存的时候往里面ADD一下就可以了
				List<CarImage> list = new ArrayList<CarImage>();
				if(uc.getAttribute(IMGLIST)!=null)
				{
					list = (List<CarImage>)uc.getAttribute(IMGLIST);
				}
				
				list.add(entity);		
				uc.setAttribute(IMGLIST, list);//按图片位置存在uc中
				request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
				forward = UPPIC;
			}
		}
		uc.setAttribute(FLAG, "1");
		logger.debug(this.getClass().getName() + "#execute was completed.");
		return mapping.findForward(forward);
	}
	/***
	 * 图片名称验证
	 */
	public boolean imageAll(FormFile file) {
		int i = 0;
		String type = file.getFileName();
		if(type.length()==0)return true;
		while (i != -1) {
			// 找到上传文件的类型的位置，这个地方的是'.'
			i = type.indexOf(".");
			/* 截取上传文件的后缀名,此时得到了文件的类型 */
			type = type.substring(i + 1).toLowerCase();
		}
		if (!type.equals("jpg") && !type.equals("jpeg")&& !type.equals("gif")){
			return true;
		}else{
			return false;
		}
	}
}
